<template>
  <div class="order-table-container">
    <!-- 设备table -->
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch">
      <el-form-item label="卡号/手机号" prop="keywords">
        <el-input v-model="queryParams.keywords" placeholder="请输入卡号/手机号" clearable style="width: 240px"
          @keyup.enter.native="handleQuery" />
      </el-form-item>
      <el-form-item label="日期范围" prop="keywords">
        <el-date-picker style="width: 240px" v-model="baseDateArr" type="daterange" range-separator="至"
          start-placeholder="开始日期" end-placeholder="结束日期" format="yyyy-MM-dd" value-format="yyyy-MM-dd">
        </el-date-picker>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-download" size="mini" @click="exportData">导出</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-table v-loading="loading" :data="tableList">
      <el-table-column label="充电编号" prop="id" />
      <el-table-column label="卡号" prop="cardNo" />
      <el-table-column label="卡类型" prop="cardType">
        <template slot-scope="scope"> 消费卡 </template>
      </el-table-column>
      <el-table-column label="抵扣金额(元)" prop="payAmount">
        <template slot-scope="scope">
          <span>{{ scope.row.payAmount / 100 }}</span>
        </template>
      </el-table-column>
      <el-table-column label="退款金额(元)" prop="refundAmount">
        <template slot-scope="scope">
          <span>{{ scope.row.refundAmount / 100 }}</span>
        </template>
      </el-table-column>
      <el-table-column label="充电桩名称" prop="siteName" />
      <el-table-column label="序列号" prop="stationSerialNum" />
      <el-table-column label="充电口" prop="stationPort">
        <template slot-scope="scope">
          {{ scope.row.stationPort / 1 + 1 }}
        </template>
      </el-table-column>
      <el-table-column label="充电状态" prop="chargeStatus">
        <template slot-scope="scope">
          <span>{{ chargingStatusMap[scope.row.chargeStatus] }}</span>
        </template>
      </el-table-column>
      <el-table-column label="充电开始时间" prop="chargeStartTime" width="150" />
      <el-table-column label="充电结束时间" prop="chargeEndTime" width="150" />
      <el-table-column label="充电时长" prop="chargeTime">
        <template slot-scope="scope">
          {{ formatDuration(scope.row.chargeTime) }}
        </template>
      </el-table-column>
      <el-table-column label="付款方" prop="phone" />
    </el-table>

    <pagination v-show="total > 0" :total="total" :page.sync="queryParams.pageNum" :limit.sync="queryParams.pageSize"
      @pagination="getList" :page-sizes="[10, 20, 30, 50, 500, 1000]" />
  </div>
</template>

<script>
import { getCardFlowAPI } from "@/api/charge/order";
import moment from "moment";
import { exportExcel, exportExcelFromAPI } from "@/utils/utils";

export default {
  name: "Order",
  data() {
    return {
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 角色表格数据
      tableList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      editVisible: false,
      // 是否显示弹出层（数据权限）
      menuExpand: false,
      menuNodeAll: false,
      deptExpand: true,
      deptNodeAll: false,
      // 日期范围
      dateRange: [],

      deviceStatusMap: {
        NORMAL: "正常",
        BREAK: "故障",
      },
      onlineStatusMap: {
        ONLINE: "在线",
        OFFLINE: "离线",
        UNREGISTER: "未注册",
      },
      chargingStatusMap: {
        FINISH: "已完成",
        CHARGING: "充电中",
        NO_PLUGGED: "未插电",
      },

      // 站点搜索关键词
      keywords: "",
      curSiteId: "",

      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        keywords: "",
      },
      baseDateArr: [
        moment().add(-1, "months").format("yyyy-MM-DD"),
        moment().format("yyyy-MM-DD"),
      ],
      // 表单参数
      form: {},

      // 表单校验
      rules: {
        siteId: [{ required: true, message: "请输入站点id", trigger: "blur" }],
      },

      // 设备收费模式
      chargeForm: {},

      // 全部站点列表
      siteList: [],

      stationData: {},
    };
  },
  created() {
    this.getList();
  },
  watch: {
    curSiteId() {
      this.getList();
    },
  },
  methods: {
    exportData() {
      exportExcelFromAPI("/order/card/flow/list/export", {
        ...this.queryParams,
        startTime:
          this.baseDateArr && this.baseDateArr[0]
            ? moment(this.baseDateArr[0]).format("YYYY-MM-DD HH:mm:ss")
            : "",
        endTime:
          this.baseDateArr && this.baseDateArr[1]
            ? moment(this.baseDateArr[1])
              .endOf("days")
              .format("YYYY-MM-DD HH:mm:ss")
            : "",
        cardTypeList: ["MONEY", "NUMBER"],
        pageNum: 1,
        pageSize: 10000,
      });
      return false;
      exportExcel({
        data: this.formatTableList(this.tableList),
        headers: [
          { label: "充电编号", key: "id" },
          { label: "卡号", key: "cardNo" },
          { label: "卡类型", key: "cardType" },
          { label: "抵扣金额(元)", key: "payAmount" },
          { label: "退款金额(元)", key: "refundAmount" },
          { label: "充电桩名称", key: "siteName" },
          { label: "序列号", key: "stationSerialNum" },
          { label: "充电口", key: "stationPort" },
          { label: "充电状态", key: "chargeStatus" },
          { label: "充电开始时间", key: "chargeStartTime" },
          { label: "充电结束时间", key: "chargeEndTime" },
          { label: "充电时长", key: "chargeTime" },
          { label: "付款方", key: "phone" },
        ],
        filename: "实体卡消费数据.xlsx",
      });
    },
    // 格式化表格数据
    formatTableList(data) {
      return data.map((item) => {
        return {
          ...item,
          payAmount: item.payAmount / 100,
          refundAmount: item.refundAmount / 100,
          chargeStatus: this.chargingStatusMap[item.chargeStatus],
          cardType: "消费卡",
          stationPort: item.stationPort / 1 + 1,
          chargeTime: this.formatDuration(item.chargeTime),
        };
      });
    },
    formatDuration(time) {
      // 参数time单位为分钟，转为秒
      let d = moment.duration(time * 60 * 1000);
      let seconds = d.seconds();
      let minutes = d.minutes();
      let hours = d.hours();
      let days = d.days();
      return `${days ? days + "天" : ""}${hours ? hours + "小时" : ""}${minutes ? minutes + "分钟" : ""
        }${seconds ? seconds + "秒" : ""}`;
    },
    // 编辑成功回调
    onEditSuccess() {
      this.editVisible = false;
      this.getList();
    },
    // 编辑关闭回调
    onEditCancel() {
      this.editVisible = false;
    },
    /** 查询列表 */
    getList() {
      this.loading = true;
      getCardFlowAPI({
        startTime:
          this.baseDateArr && this.baseDateArr[0]
            ? moment(this.baseDateArr[0]).format("YYYY-MM-DD HH:mm:ss")
            : "",
        endTime:
          this.baseDateArr && this.baseDateArr[1]
            ? moment(this.baseDateArr[1])
              .endOf("days")
              .format("YYYY-MM-DD HH:mm:ss")
            : "",
        cardTypeList: ["MONEY", "NUMBER"],
        ...this.queryParams,
      }).then((res) => {
        this.tableList = res.rows;
        this.total = res.total;
        this.loading = false;
      });
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.dateRange = [];
      this.resetForm("queryForm");
      this.handleQuery();
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      this.$modal
        .confirm("确认删除吗？")
        .then(function () {
          return deleteAPI([row.id]);
        })
        .then(() => {
          this.getList();
          this.$modal.msgSuccess("删除成功");
        })
        .catch(() => { });
    },
    /** 跳转详情页 */
    toDetail(row) {
      this.$router.push({
        path: "station/edit",
        query: {
          stationName: row.stationName,
        },
      });
    },
  },
};
</script>
<style scoped lang="scss">
.site-list-container {
  width: 20%;
  flex: none;
  margin-right: 20px;

  .site-list-wrapper {
    position: relative;
    overflow: hidden;

    .site-search {
      position: absolute;
      top: 0;
      margin-bottom: 20px;
    }

    .site-list {
      margin-top: 40px;
      overflow: auto;

      .site-btn {
        width: 100%;
        font-size: 12px;
        color: #606266;
        padding: 9px 15px;
        text-align: left;
        border-radius: 2px;
        cursor: pointer;

        &:hover {
          color: #1890ff;
          background-color: #e8f4ff;
        }

        &.selected {
          color: #1890ff;
          background-color: #e8f4ff;
        }
      }
    }
  }
}

.station-list-container {
  width: 80%;
  flex: auto;
}
</style>
